package com.have.blog.xo.service.admin.impl;

import com.github.pagehelper.PageHelper;
import com.have.blog.base.enums.BlogStatus;
import com.have.blog.commons.feign.PictureFeignClient;
import com.have.blog.model.api.CommonPage;
import com.have.blog.model.mapper.TUserMapper;
import com.have.blog.model.models.TUser;
import com.have.blog.model.models.TUserExample;
import com.have.blog.utils.MD5Utils;
import com.have.blog.utils.MyStringUtils;
import com.have.blog.utils.ResultUtils;
import com.have.blog.xo.constant.MessageConstant;
import com.have.blog.xo.constant.SysConstant;
import com.have.blog.xo.service.admin.BlogUserService;
import com.have.blog.xo.service.admin.SystemParamService;
import com.have.blog.xo.uitls.WebUtil;
import com.have.blog.xo.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
@SuppressWarnings("all")
public class BlogUserServiceImpl implements BlogUserService {
    @Autowired
    private TUserMapper userMapper;
    @Autowired
    private PictureFeignClient pictureFeignClient;
    @Autowired
    private WebUtil webUtil;
    @Autowired
    private SystemParamService systemParamService;

    @Override
    public String getPageList(UserVo userVO) {
        PageHelper.startPage(userVO.getCurrentPage(), userVO.getPageSize());
        TUserExample example = new TUserExample();
        TUserExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        if (!StringUtils.isEmpty(userVO.getKeyword()) && !StringUtils.isEmpty(userVO.getKeyword().trim())) {
            criteria.andNickNameLike("%" + userVO.getKeyword() + "%");
        }
        if (!StringUtils.isEmpty(userVO.getSource()) && !StringUtils.isEmpty(userVO.getSource().trim())) {
            criteria.andSourceEqualTo(userVO.getSource());
        }
        if (userVO.getCommentStatus() != null) {
            criteria.andCommentStatusEqualTo(userVO.getCommentStatus());
        }
        if(!StringUtils.isEmpty(userVO.getOrderByAscColumn())) {
            // 将驼峰转换成下划线
            String column = MyStringUtils.underLine(new StringBuffer(userVO.getOrderByAscColumn())).toString();
            example.setOrderByClause(column + " asc");
        } else if(!StringUtils.isEmpty(userVO.getOrderByDescColumn())) {
            // 将驼峰转换成下划线
            String column = MyStringUtils.underLine(new StringBuffer(userVO.getOrderByDescColumn())).toString();
            example.setOrderByClause(column + " desc");
        } else {
            example.setOrderByClause("create_time desc");
        }
        List<TUser> userList = userMapper.selectByExample(example);

        // 获取用户头像
        StringBuilder sb = new StringBuilder();
        userList.forEach(item ->{
            if (!StringUtils.isEmpty(item.getAvatar())) {
                sb.append(item.getAvatar() + SysConstant.FILE_SEGMENTATION);
            }
        });

        Map<String, String> pictureMap = new HashMap<>();
        String pictureResult = null;
        if (!StringUtils.isEmpty(sb.toString())) {
            pictureResult = pictureFeignClient.getPicture(sb.toString(), SysConstant.FILE_SEGMENTATION);
        }
        if (pictureResult != null) {
            List<Map<String, Object>> picList = webUtil.getPictureMap(pictureResult);
            picList.forEach(item -> {
                pictureMap.put(item.get(SysConstant.UID).toString(), item.get(SysConstant.URL).toString());
            });
            for (TUser user : userList) {
                if (!StringUtils.isEmpty(user.getAvatar())) {
                    List<String> tempPicUidList = MyStringUtils.changeStringToStringList(user.getAvatar(), SysConstant.FILE_SEGMENTATION);
                    List<String> tempPicUrlList = new ArrayList<>();
                    tempPicUidList.forEach(item -> {
                        if (pictureMap.get(item) != null) {
                            tempPicUrlList.add(pictureMap.get(item));
                        }
                    });
                    user.setPhotoUrl(tempPicUrlList);
                }
            }
        }
        return ResultUtils.successWithData(CommonPage.restPage(userList));
    }

    @Override
    public String addUser(UserVo userVO) {
        TUser user = new TUser();
        // 字段拷贝【将userVO中的内容拷贝至user】
        BeanUtils.copyProperties(userVO, user, SysConstant.STATUS);
        String defaultPassword = systemParamService.getSystemParamValueByKey(SysConstant.SYS_DEFAULT_PASSWORD);
        user.setPassWord(MD5Utils.string2MD5(defaultPassword));
        user.setSource("YUEQIAN");
        user.setUid(MyStringUtils.getUUID());
        user.setStatus(BlogStatus.ENABLE.getStatus());
        user.setStartEmailNotification(0);
        int result = userMapper.insert(user);
        if (result < 1) {
            return ResultUtils.errorWithMessage(MessageConstant.INSERT_FAIL);
        }
        return ResultUtils.successWithMessage(MessageConstant.INSERT_SUCCESS);
    }

    @Override
    public String editUser(UserVo userVO) {
        TUser user = userMapper.selectByPrimaryKey(userVO.getUid());
        user.setUserName(userVO.getUserName());
        user.setEmail(userVO.getEmail());
        user.setStartEmailNotification(userVO.getStartEmailNotification());
        user.setOccupation(userVO.getOccupation());
        user.setGender(userVO.getGender());
        user.setQqNumber(userVO.getQqNumber());
        user.setSummary(userVO.getSummary());
        user.setBirthday(userVO.getBirthday());
        user.setAvatar(userVO.getAvatar());
        user.setNickName(userVO.getNickName());
        user.setUserTag(userVO.getUserTag());
        user.setCommentStatus(userVO.getCommentStatus());
        user.setUpdateTime(new Date());
        int result = userMapper.updateByPrimaryKeySelective(user);
        if (result < 1) {
            return ResultUtils.errorWithMessage(MessageConstant.UPDATE_FAIL);
        }
        return ResultUtils.successWithMessage(MessageConstant.UPDATE_SUCCESS);
    }

    @Override
    public String deleteUser(UserVo userVO) {
        TUser user = userMapper.selectByPrimaryKey(userVO.getUid());
        user.setStatus(BlogStatus.DISABLE.getStatus());
        user.setUpdateTime(new Date());
        int result = userMapper.updateByPrimaryKeySelective(user);
        if (result < 1) {
            return ResultUtils.errorWithMessage(MessageConstant.DELETE_FAIL);
        }
        return ResultUtils.successWithMessage(MessageConstant.DELETE_SUCCESS);
    }

    @Override
    public String resetUserPassword(UserVo userVO) {
        String defaultPassword = systemParamService.getSystemParamValueByKey(SysConstant.SYS_DEFAULT_PASSWORD);
        TUser user = userMapper.selectByPrimaryKey(userVO.getUid());
        user.setPassWord(MD5Utils.string2MD5(defaultPassword));
        user.setUpdateTime(new Date());
        int result = userMapper.updateByPrimaryKeySelective(user);
        if (result < 1) {
            return ResultUtils.errorWithMessage(MessageConstant.OPERATION_FAIL);
        }
        return ResultUtils.successWithMessage(MessageConstant.OPERATION_SUCCESS);
    }
}
